var productExceptSelf = function (nums) {
    const answer = new Array(nums.length);

    // 计算每个元素左侧所有元素的乘积
    let leftProduct = 1;
    for (let i = 0; i < nums.length; i++) {
        answer[i] = leftProduct;
        leftProduct *= nums[i];
    }

    // 计算每个元素右侧所有元素的乘积，并与左侧乘积相乘得到结果
    let rightProduct = 1;
    for (let i = nums.length - 1; i >= 0; i--) {
        answer[i] *= rightProduct;
        rightProduct *= nums[i];
    }

    return answer;
};

// 示例用法
const nums = [1, 2, 3, 4];
console.log(productExceptSelf(nums)); // 输出 [24,12,8,6]